﻿/*
    Autor : Roger Medeiros
    Data  : 01/02/2012
    Site  : www.interacaosistemas.com.br
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading;
using Ionic.Zip;

namespace i9PgAdmin.Core
{
    public class Dump
    {
        public Conexao conexao { get; set; }
        public string DirPg { get; set; }
        public string Destino { get; set; }
        public bool Comprimir { get; set; }

        public Dump()
        {
            this.conexao = new Conexao();
        }

        public string IniciaDump()
        {
            try
            {
                Environment.SetEnvironmentVariable("PGPASSWORD", this.conexao.Senha);
                this.Destino = conexao.CaminhoDump;
                this.Comprimir = conexao.Comprimir;

                string backupFile = this.Destino + this.conexao.Database + "_" + DateTime.Now.ToString("yyyyMMdd_HHmm") + ".backup";
                string BackupString = "-ibv -Z3 -f \"" + backupFile + "\" " + "-Fc -h " + this.conexao.Servidor + " -U " + this.conexao.Usuario + " -p " + this.conexao.Porta.ToString() + " " + this.conexao.Database;

                var proc = new System.Diagnostics.Process();
                proc.StartInfo.FileName = this.conexao.CaminhoBin + "\\pg_dump.exe";
                proc.StartInfo.Arguments = BackupString;
                proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                proc.Start();
                proc.WaitForExit();
                proc.Close();

                if (this.Comprimir)
                {
                    this.ComprimeBackup(backupFile);
                }

                return backupFile;
            }
            catch (Exception ex)
            {
                throw new Exception("Um erro ocorreu ao efetuar o Backup.\n\nErro : " + ex.Message);
            }
        }

        private void ComprimeBackup(string Arquivos)
        {
            using (ZipFile zip = new ZipFile())
            {
                zip.AddFile(Arquivos, "");
                zip.Comment = @"
-- PostgreSQL Dump ------------------------------------------
-- Gerado pelo i9PgAdmin
-- www.interacaosistemas.com.br
-------------------------------------------------------------";
                var destino = Arquivos.Replace(".backup", ".zip").Trim();
                zip.Save(destino);
            }
            return;
        }
    }
}
